package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: DELL
 * Date: 2023-03-26
 * Time: 9:57
 */

// 在主页中, 统计当前用户名(userId) 更新对应的文章数目
    @WebServlet("/count")
public class CountBlog extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 约定前端: HTTP:/1.1 Get application/json
        // 约定后端: 后端将查询到的博客数目传给前端, 前端进行更新

        ObjectMapper objectMapper = new ObjectMapper();
        // 获取当前会话状态
        HttpSession session = req.getSession(false);
        if(session == null) {
            return;
        }
        // 根据会话获取当前 user
        User user = (User) session.getAttribute("user");
        if(user == null) {
            return;
        }
        BlogDao blogDao = new BlogDao();
        // 根据 userId 查询当前用户的博客数目

        int count = blogDao.countBlogByUserId(user.getUserId());
        resp.setContentType("application/json; charset = utf8");
        String respJson = objectMapper.writeValueAsString(count);
        resp.getWriter().write(respJson);
    }
}
